from django.shortcuts import render, redirect, get_object_or_404
from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from usermanagerapp.models import User


# Create your views here.

# 响应函数请求
def index(request):
    print(request.method)
    print(request.path)
    print(request.GET)
    print(request.POST)
    #  返回一个包含字符串的响应
    return render(request, "index.html")


def login(request):

    if request.method == "POST":
        print("login 登录请求")
        print(request.POST)
        return HttpResponse(request.POST["username"])
    else:
        print("login 登录页")
        return render(request, "login.html")

# @csrf_exempt
def post_json(request):
    if request.method == "POST":
        print("post_json 接收到 POST 请求")
        print(request.body.decode('utf-8'))
        return HttpResponse("POST 请求成功")
    else:
        return HttpResponse("只能处理post请求")




@csrf_exempt
#  POST 请求
def addUser_post(request):
    if request.method == "POST":
        print("addUser_post 接收到 POST 请求")
        # 从请求中获取数据，name,sex,mail
        name = request.POST.get('name')
        sex = request.POST.get('sex')
        mail = request.POST.get('mail')
        print(name, sex, mail)
        if name is None or sex is None or mail is None:
            return HttpResponse("参数错误")

        user = User()
        user.name = name
        user.sex = sex
        user.mail = mail
        user.save()

        # 返回添加的用户到页面
        # return HttpResponse(f"添加用户成功:{name},{sex},{mail}")
        # 转到 listUser 请求
        return redirect('listUser')
    else:
        # 打开页面 addUser.html
        return render(request, "addUser.html")
        # return HttpResponse("只能处理post请求")


def showAllUsers(request):
    users = User.objects.all()
    response = ""
    # 循环迭代users
    for user in users:
        # 拼接字符串response
        response += f"{user.name},{user.sex},{user.mail}<br>"

    # 直接显示在页面
    return HttpResponse(response)

def queryUser(request):
    users = User.objects.filter(name='张三')
    response = ""
    for user in users:
        response += f"{user.name},{user.sex},{user.mail}<br>"

    return HttpResponse(response)

def updateUser(request):
    response = ""
    User.objects.filter(name='张三').update(name='张三丰')
    users = User.objects.filter(name='张三丰')
    for user in users:
        response += f"{user.name},{user.sex},{user.mail}<br>"
    return HttpResponse( response)



# 添加
def addUser(request):
    # 如果是get请求
    if request.method == "GET":
        # 打开页面 addUser.html
        return render(request, "addUser.html")
    elif request.method == "POST":
        print("addUser_post 接收到 POST 请求")
        # 从请求中获取数据，name,sex,mail
        name = request.POST.get('name')
        sex = request.POST.get('sex')
        mail = request.POST.get('mail')

        user = User()
        user.name = name
        user.sex = sex
        user.mail = mail
        user.save()

        # 返回添加的用户到页面
        # return HttpResponse(f"添加用户成功:{name},{sex},{mail}")
        # 转到 listUser 请求
        return redirect('listUser')

# 删除
def deleteUser(request,user_id):
    user = get_object_or_404(User, id=user_id)
    user.delete()
    return redirect('listUser')  # 跳转到用户列表页

# 列表
def listUser(request):
    # 获取所有用户
    users = User.objects.all().order_by('-id')

    # 每页显示的记录数
    paginator = Paginator(users, 5)  # 这里设置每页显示5条记录

    # 获取当前请求的页码，默认为1
    page_number = request.GET.get('page', 1)

    try:
        # 获取指定页码的用户列表
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        # 如果页码不是整数，则返回第一页
        page_obj = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，则返回最后一页
        page_obj = paginator.page(paginator.num_pages)

    # 将分页后的用户对象传递给模板
    return render(request, "listUser.html", {"users": page_obj}) # 渲染页面

# 修改
def editUser(request,user_id):
    if request.method == 'GET':
        # 打开页面 editUser.html
        user = get_object_or_404(User, id=user_id)
        return render(request, 'editUser.html', {'user': user})
    elif request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        user.name = request.POST.get('name')
        user.sex = request.POST.get('sex')
        user.mail = request.POST.get('mail')
        user.save()
        return redirect('listUser') # 跳转请求到listUser
